// pages/livePlayer/index.ts
const app = getApp();
let config = require("../../utils/config");
let utils = require("../../utils/util.js");
import { http } from "../../utils/request";
import { SocketTask } from "../../utils/websocket";
// import { mqtt } from "../../utils/mqttsocket";
const WxParse = require("../../components/wxParse/wxParse");
let player = "";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    topHeight: 0,
    menuBtnHeight: 0,
    navCurrent: 0,
    navs: ["活 动", "聊 天", "邀请榜", "介 绍"],
    userRole: false, //用户身份 默认普通用户
    po: "",//房间编号
    roomInfo: "", //直播详情
    roomExtend: "",
    liveStatus: 0, //直播状态 //10未开始，20直播中，30已结束  40已暂停, 99已禁用
    noticeList: [1], //系统通知
    chatMsgTop: 0,
    chatMsgList: [], //聊天消息
    inputShow: false, //控制输入框显示
    isFocus: false, //聊天框获取焦点
    noChat: true, //是否禁言
    inputVal: "", //聊天内容
    inputHeight: 20, //软键盘的高度

    startTimer: "", //直播开始倒计时器
    endTimer: "", //直播计时器，用于判断直播是否结束
    surplusTime: 0, //距开始直播剩余的时间秒数
    timeArr: [0, 0, 0, 0],  //倒计时数组[天，时，分，秒]
    showShare: false, //分享弹窗
    rankingList: [], //排行榜列表
    rankingMe: "",  //本人邀约信息
    showPacket: false, //领取结果
    showRedBg: false, //领取前红包
    answerKey: "", //问题答案
    answerInfo: "",//题目信息
    seeTotal: 0, //观看总时长
    seeTime: 0, //本地观看时长
    redTimer: "", //直播计时器（领奖励）
    // redArr: [0,0,0,0],  //倒计时数组[天，时，分，秒]
    redArr: "",  //距离领取奖励的时长
    robAward: "", //抢到的红包金额，或者积分数

    inviteAppletId: "", //店长标识
    inviteCode: "", //邀请码
    online: 0, //在线人数
    laudNum: 0, //点赞总数
    laudCurrent: 0, //点赞控制active的
    isRotate: false,  //视频横竖选择
    playStatus: false, //拉流：网络接收到首个视频数据包（为解决开始推流，到显示画面之间的短暂黑屏）

    isLiveExam: false, //是否回答过题
    playUrl: "", //拉流地址
    usePlayUrl: "", //

    liveMuted: false, //直播是否静音
    posterShow: false,//是否展示广告
    posterLoop: false, //广告是否循环播放
    posterTimer: "", //广告倒计时
    posterCount: 0, //广告时长

    comein: "",
    showComein: false,
    askTop: 0, //答题内容滚动距顶部的距离
    videoCurrent: 0, //记录回放观看的进度

    enterType: 1, //进来时的直播状态（1未开始，2直播中，3回放）
    enterTime: "", //进入的时间
    leaveTime: "", //离开的时间

    exitTimeout: "",
    isEnter: false, //进来、离开的标识
    isReply: false, //观看时长达到，随机提前开放答题
    platform: "", //平台类型
    shareFlag: false,  //直播间默认不可转发（适用于普通用户）
    D_Value: 0,  //服务器时间和手机时间之间的差值 （手机时间不准，导致直播提前或推迟结束）

    couponData: null, //礼券信息
    couponTime: -1, //展示礼品券的播放时长位置
    clickGet: false, //防止多次快速点击领取券
    showGift: false, //礼券领取提示窗
    showCoupon: false,  //已领取的礼品券弹窗
    couponList: [], //已领取的礼品券
  },

  /** 聊天，邀请榜切换 */
  changeNavTap(e) {
    let current = e.currentTarget.dataset.index;
    this.setData({
      navCurrent: current
    })
    if (current == 2) {
      this.queryRanking();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    wx.hideShareMenu(); //禁止右上角原生转发
    app.globalData.playbacks = wx.getStorageSync('playbacks') ? wx.getStorageSync('playbacks') : []; //回放观看记录
    app.globalData.playbacks.forEach(item => {
      if (item.po == e.po) {
        this.data.videoCurrent = item.current;  //当前房间，回放观看的进度
      }
    })
    this.setData({
      po: e.po,
      playUrl: e.pull,
      usePlayUrl: e.pull,
      inviteCode: e.invite ? e.invite : "",
      topHeight: wx.getMenuButtonBoundingClientRect().top,
      menuBtnHeight: wx.getMenuButtonBoundingClientRect().height,
      videoCurrent: this.data.videoCurrent,
    });


  },

  /**直播详情 */
  queryLiveDetails() {
    let that = this;
    http.requestData("GET", "Live/GetRoomItem", {
      PO: this.data.po
    }, true).then(res => {
      if (res.Tag == 10) {
        wx.setNavigationBarTitle({
          title: res.Data.Name,
        })
        //房间名称最多展示9字
        res.Data.Name = res.Data.Name.length > 9 ? res.Data.Name.substr(0, 9) + "..." : res.Data.Name
        res.Data.Cover = res.Data.Cover ? config.hostUrl + res.Data.Cover : "/images/default.png"; //封面图
        res.Data.Warm = res.Data.Warm ? config.hostUrl + res.Data.Warm : "/images/room/bg-live-room.png"; //暖场背景图
        if (res.Data.Dvr && res.Data.Dvr.indexOf("https") == -1) {//回放地址里不带https,  需加上服务器域名
          res.Data.Dvr = config.playUrl + res.Data.Dvr;
        }
        // res.Data.Dvr = "https://dvrhw.huachuangshidai.com/VO202405050111/s16508640061123895.mp4";
        if (res.Data.AdFileSrc) {//广告地址
          res.Data.AdFileSrc = config.hostUrl + res.Data.AdFileSrc;
        }
        if (res.Data.Introduce) {
          WxParse.wxParse('live', 'html', res.Data.Introduce, that);
        }
        that.setData({
          roomInfo: res.Data,
          roomExtend: res.Extend,
          userRole: res.Extend.Manager,
          inviteCode: res.Extend.MangerId,
          online: res.Extend.OnLine,
          liveStatus: res.Data.Status,
          seeTotal: res.Data.Status==30?res.Extend.OnVideo:(that.data.seeTime?that.data.seeTime:res.Extend.OnVideo),
          isLiveExam: that.getCacheExam(that.data.po) ? that.getCacheExam(that.data.po) : res.Extend.IsExam, //是否答题
          liveMuted: res.Data.AdFileSrc && res.Data.Status == 10 ? true : false,
          posterShow: res.Data.AdFileSrc && res.Data.Status == 10 ? true : false,
          enterType: res.Data.Status == 10 ? 1 : (res.Data.Status == 20 ? 2 : 3),
          enterTime: utils.formatTime(new Date()),
          answerInfo: res.Extend.Exam,
          shareFlag: res.Data.IsRelay == 1 ? true : false,
          D_Value:  parseInt(new Date(res.Extend.Time).getTime()/1000) - parseInt(new Date().getTime()/1000)
        })
        // console.log("时间差：", that.data.D_Value)
        //直播未开始倒计时
        if (res.Data.Status == 10) {
          let timeNow = utils.formatTime(new Date(res.Extend.Time)); //服务器当前时间
          that.countDownStart(res.Data.Stime, timeNow); //距开播倒计时
          if (res.Data.AdFileSrc) {//有广告
            that.countPoster(res.Data.AdTimeInt); //广告倒计时
            if (res.Data.AdType == 20) {//音频广告
              let audioCtx = wx.createAudioContext('myAudio');
              audioCtx.play();
            }
          }
        }
        if (that.data.liveStatus != 30) {
          //每个分钟请求一次
          that.twoMins();
        }
        //直播计时器 (可领奖励条件 that.data.seeTotal < res.Extend.WatchingSee)
        if (that.data.liveStatus != 10) {
          that.countDownRed();
        }
      } else {
        http.showToast(res.Message);
      }
    }).catch(e => {
    })
  },

  /** 广告倒计时 */
  countPoster(count) {
    this.data.posterCount = count
    this.data.posterTimer = setInterval(() => {
      if (this.data.posterCount-- == 0) {
        clearInterval(this.data.posterTimer);
        this.setData({
          posterShow: false,
          liveMuted: false
        })
        return;
      }
      this.setData({
        posterCount: this.data.posterCount
      })
    }, 1000);

  },

  /** 直播未开始倒计时 */
  countDownStart(endTime, startTime) {
    let that = this;
    let currentTime = utils.computeTimes(endTime, startTime);
    that.data.startTimer = setInterval(() => {
      if (currentTime-- <= 0) {//开始推流
        //清除计时器
        clearInterval(that.data.startTimer);
        that.countDownOver();
      } else {
        that.setData({
          surplusTime: currentTime,
          timeArr: utils.countTimes(currentTime)
        })
      }
    }, 1000);

  },

  // 直播倒计时结束，开播
  countDownOver() {
    this.setData({
      liveMuted: false,
      posterShow: false,
      seeTotal: 0,  //开始推流观看时长从0开始
      liveStatus: 20,
      enterType: 2,
      enterTime: utils.formatTime(new Date()), //本地记录开始观看时间
      playUrl: this.data.usePlayUrl,
      playStatus: true
    })
    this.countDownRed(); //直播计时器
    setTimeout(() => {
      player.play(); //如果直播没有自动播放，这里再次手动播放流
    }, 2000);
  },

  //没隔1分钟请求一次
  twoMins() {
    let that = this;
    that.setData({
      enterTime: utils.formatTime(new Date()),
    })
    if (that.data.liveStatus == 30) {
      clearTimeout(that.data.exitTimeout);
      return;
    }
    that.data.exitTimeout = setTimeout(() => {
      //当前直播间处于桌面前端（非onhide状态），才保存计时
      if (that.data.isEnter) {
        that.savePlayTimeV2();
      }
      that.twoMins();
    }, 60000);
  },

  /** 初始连接mqtt */
  connectMQTT() {
    // mqtt.connectMQTT(utils.generateGuid(),config.OPENID(), function(topic,msg){
    //   console.log(topic,msg)
    //   if(topic == config.OPENID()){
    //   }
    // });
  },

  /** 初始连接socket */
  connectSocket() {
    let that = this;
    SocketTask.initWebSocket(config.OPENID(), this.data.po, res => {
      that.receiveMsg(res);
    })
  },

  /** 接收socket消息 处理 */
  receiveMsg(res) {
    // console.log("socket 接收消息：",res)
    let that = this;
    if (this.data.po != res.po) {
      return
    }
    switch (parseInt(res.type)) {
      case 1: //聊天
        this.data.chatMsgList.push(res);
        this.setData({
          chatMsgList: this.data.chatMsgList,
          chatMsgTop: this.data.chatMsgList.length * 100
        })
        break;
      case 2: //直播开始推流
        // this.setData({
        //   liveMuted: false,
        //   posterShow: false,
        //   seeTotal: 0,  //开始推流观看时长从0开始
        //   liveStatus: 20,
        //   enterType: 2,
        //   enterTime: utils.formatTime(new Date()), //本地记录开始观看时间
        // })
        // if(this.data.seeTotal<this.data.roomExtend.WatchingSee){
        //   this.countDownRed();//答题领红包倒计时
        // }
        this.setData({
          playUrl: this.data.usePlayUrl,
        })
        player.play(); //播放流
        break;
      case 3: //直播结束推流
        // if(this.data.roomInfo.Model==10){
        //   this.livePlayOver();
        // }
        break;
      case 4: //在线人数
        this.setData({
          online: res.msg
        })
        break;
      case 5: //点赞
        this.setData({
          laudNum: res.msg
        })
        break;
      case 6: //直播暂停推流
        this.setData({
          liveStatus: 40,
          isRotate: false, //退出全屏
          playStatus: false,
          playUrl: "rtmp://127.0.0.1", //更新拉流地址 停止播放
        })
        break;
      case 7: //某某进来了
        // this.setData({
        //   comein: res.name,
        //   showComein: true,
        // })
        // setTimeout(() => {
        //   this.setData({
        //     showComein: false,
        //   })
        // }, 1000);
        break;
      case 8: //店长设置保存活动（红包或积分）后，更新活动相关数据
        this.queryExam(); //获取答题库
        if (res.msg) {
          let resMsg = JSON.parse(res.msg);
          //当前客户是不是被此店长邀请的
          if (this.data.inviteCode == resMsg.m) {
            this.data.roomInfo.IsActive = resMsg.r.IsActive;
            this.data.roomInfo.IsExam = resMsg.r.IsExam;
            this.data.roomExtend.WatchingSee = resMsg.r.WatchingSee;
            this.data.roomExtend.IsSaveActive = resMsg.isSaveActive;
            this.setData({
              roomInfo: this.data.roomInfo,
              roomExtend: this.data.roomExtend
            })
          }
        }
        break;
      default:
        break;
    }
  },

  /**
  * 直播状态变化事件
  * @param {*} e 
  */
  stateChangeTap(e) {
    // 2001	拉流：已经连接服务器
    // 2002	拉流：已经连接 RTMP 服务器,开始拉流
    // 2003	拉流：网络接收到首个视频数据包(IDR)
    // 2004	拉流：视频播放开始
    // 2006	拉流：视频播放结束
    // 2007	拉流：视频播放Loading
    // 2032	拉流：视频渲染首帧事件
    // 2101	拉流：当前视频帧解码失败
    // 2104	拉流：网络来包不稳：可能是下行带宽不足，或由于主播端出流不均匀
    // 2105	拉流：当前视频播放出现卡顿
    // 2107	拉流：当前视频帧不连续，可能丢帧
    // -2302	拉流：获取拉流地址失败
    // console.log('live-player code:', e.detail.code)
    if (e.detail.code == 2004) {
      this.setData({
        liveStatus: 20,
        playStatus: true
      })
    }

  },

  /** 直播结束处理 */
  livePlayOver(){
    clearInterval(this.data.redTimer); //清除直播计时器
    clearTimeout(this.data.exitTimeout);
    this.setData({
      liveStatus: 30,
      isRotate: false, //退出全屏
      playStatus: false,
      playUrl: "rtmp://127.0.0.1", //更新拉流地址 停止播放
    })
    this.removeSeeTime();
    this.leaveStopPlay();
    this.saveLeavePlaying();
  },

  /**
     * 直播计时器（领取奖励）
     */
  countDownRed() {
    let that = this;
    if(that.data.redTimer){
      clearInterval(that.data.redTimer); //先清除，防止重复计时
    }
    // 一进直播间，展示剩余多少分钟可领奖励
    if(that.data.seeTotal<that.data.roomExtend.WatchingSee){
      let sen = that.data.roomExtend.WatchingSee - that.data.seeTotal;
      let len = utils.countTimes(sen);
      if(parseInt(len[1])>0){//答题时长达到小时
        that.data.redArr = len[1] + ":" + len[2] + ":" + len[3]
      }else{
        that.data.redArr = len[2] + ":" + len[3]
      }
      that.setData({
        redArr: that.data.redArr
      })
    }
    
    // 直播计时更新观看时长
    that.data.redTimer = setInterval(() => {
      // && that.data.roomInfo.Model==20; //录播类型
      if(that.data.liveStatus == 20){//录播直播中
        let start = that.data.roomInfo.Stime; //直播开始时间
        //直播已进行的时长, 手机当前时间和开播的时间计算，然后再加上当前时间与服务器的时间差值
        let currentTime = utils.computeTimes(utils.formatTime(new Date()),start,true) + that.data.D_Value; 
        // console.log("直播进行时长",currentTime);
        //礼品券时长比较
        // if(currentTime>=that.data.couponTime && that.data.couponTime>-1){
        //   let coupon = that.data.couponData;
        //   if(coupon && coupon.UseLimit){//还可以继续领
        //     that.setData({
        //       showGift: true
        //     })
        //   }else{
        //     that.setData({
        //       showGift: false
        //     })
        //   }
        // }
        //直播结束的总时长比较
        if(that.data.roomInfo.OnPushUrlTime){
          let hms = that.data.roomInfo.OnPushUrlTime.split(":");
          let longTime = Number(hms[0])*3600 + Number(hms[1])*60 + Number(hms[2]); //将总时长转化成秒数
          // console.log("直播总时长",longTime);
          if(currentTime>=longTime){//已结束
            that.livePlayOver();
          }
        }
      }

     /**
     * isLiveExam 已参与过活动
     * IsActive==0 活动未开启
     * IsSaveActive==0 活动未设置
     * IsSaveActive==3：活动设置类型为不设置活动
     */
      if (that.data.isLiveExam || that.data.roomInfo.IsActive == 0 || that.data.roomExtend.IsSaveActive == 0) {
        // console.log("*未达到参会活动条件*")
        return
      }
     
      if (that.data.seeTotal++ >= that.data.roomExtend.WatchingSee) {
        // clearInterval(that.data.redTimer);
        if (!that.data.isLiveExam) {//没有参与过活动
          if (that.data.roomInfo.IsExam) {//设置了答题
            setTimeout(() => {
              if (that.data.liveStatus == 20) {
                that.setData({
                  isReply: true  //可以随机提前答题
                })
              }
            }, (Math.random() * 1000 * 300 + 1).toFixed(0));  //5分钟内随机延迟答题
          } else {
            //未设置答题，设置了活动奖励，则直接领取奖励
            if(that.data.roomExtend.IsSaveActive != 3){
              that.setData({
                showRedBg: true
              })
              setTimeout(() => {
                that.setData({
                  askTop: 250
                })
              }, 250);
            }
          }
        }
      }else {
        let sen = that.data.roomExtend.WatchingSee - that.data.seeTotal;
        let len = utils.countTimes(sen);
        if(parseInt(len[1])>0){//答题时长达到小时
          that.data.redArr = len[1] + ":" + len[2] + ":" + len[3]
        }else{
          that.data.redArr = len[2] + ":" + len[3]
        }
        that.setData({
          redArr: that.data.redArr
        })
        
      }
      that.setData({
        seeTotal: that.data.seeTotal
      })
    }, 1000);
  },

  /** 去抽奖 */
  luckDrawTap() {
    // return http.showToast("敬请期待")
    http.href("/pages/luckDraw/index?po=" + this.data.po);
  },

  /** 领取奖励 */
  robPacketTab() {
    this.setData({
      showRedBg: false
    })
    this.robRedPacket();
    return;
    if (!this.data.roomExtend) {
      return;
    }
    if (this.data.seeTotal < this.data.roomExtend.WatchingSee) {
      return http.showToast("请继续观看");
    }
    if (this.data.roomInfo.IsExam == 1) { //设置了答题
      this.queryExam();
    } else {
      this.robRedPacket();
    }

  },

  /** 邀请榜 */
  queryRanking() {
    let that = this;
    http.requestData("GET", "InviteHistory/GetList", {
      po: this.data.po
    }).then(res => {
      if (res.Tag == 10) {
        that.setData({
          rankingList: res.Data,
          rankingMe: res.Extend,
        })
      } else {
        http.showToast(res.Message)
      }
    })
  },

  /** 转发分享 */
  moreTap() {
    this.setData({
      showShare: true
    })
  },

  /** 点赞 */
  laudTap() {
    this.translate();
    http.requestData("GET", "Live/Like", {
      po: this.data.po
    }).then(res => { })
  },

  /** 问答题 */
  changeAnswer(e) {
    if (this.data.isLiveExam) {
      return;
    }
    this.setData({
      answerKey: e.currentTarget.dataset.answer
    })
  },

  /** 券 */
  couponTap(){
    let that = this;
    http.requestData("GET","Coupon/GetApiPageList",{
      Id: "", //礼品券id
      code: "",//核销码
      po: this.data.po,
      MemberId: config.UID(), //用户id
      Status: 10, //10 未使用， 20 已核销，30 已过期
      PageIndex: 1,
      PageSize: 100
    }).then(res=>{
      if(res.Tag=="10"){
        if(res.Data){
          that.setData({
            couponList: res.Data,
            showCoupon:true
          })
        }
      }else{
        http.showToast(res.Message);
      }
    }).catch(err=>{
      http.showToast("服务器繁忙")
    })
  },

  /** 领取礼品券 */
  getCouponTap(){
    let that = this;
    if(that.data.clickGet){
      return;
    }
    that.data.clickGet = true;
    http.requestData("POST","Coupon/GetCoupon",{
      "po": this.data.po,
      "poName": this.data.roomInfo.Name,
      "poStime": this.data.roomInfo.Stime,
      "couponId": this.data.couponData.Id,
      "couponName": this.data.couponData.Name,
      "couponRemark": this.data.couponData.Remark,
      "mangerId": this.data.roomExtend.MangerId,
    }).then(res=>{
      if(res.Tag==10){
        if(res.Data){
          http.showToast("领取成功");
          that.setData({
            couponData: res.Data,
            showGift: res.Data.UseLimit?true:false
          })
        }
      } else if(res.Tag==11){
        http.showToast("太火爆了，再次尝试");
      }else if(res.Tag==100){ //已领完
        http.showToast("已被领取完");
        that.setData({
          couponData: res.Data,
          showGift: false
        })
      }else{
        http.showToast(res.Message)
      }
      that.data.clickGet = false;
    }).catch(err=>{
      that.data.clickGet = false;
    })
  },

  /** 关闭弹窗 */
  cancelMask() {
    this.setData({
      showShare: false,
      showPacket: false,
      showCoupon: false
    })
  },

  /** 试题提交答案 */
  confirmAnswer() {
    let that = this;
    if (!this.data.answerKey) {
      return http.showToast("请选择答案")
    }
    this.setData({
      isLiveExam: true //先设置已参与活动状态
    })

    // let message = {
    //   Type: 1,
    //   PO: this.data.po,
    //   AppletId: config.OPENID(),//openid
    //   Data: {
    //     po: this.data.po,
    //     manageId: this.data.inviteCode, //邀请码
    //     examId: this.data.answerInfo.Id, //试题id
    //     answerResult: this.data.answerKey == this.data.answerInfo.Answer?20:30, //选择的试题答案
    //     activeType: this.data.roomExtend.IsSaveActive==1?"10":(this.data.roomExtend.IsSaveActive==2?"20":"30") // 活动类型
    //   }
    // }
    // mqtt.send("v1",JSON.stringify(message));
    // return
    //无论答题对或错，都保存答题记录
    this.saveExamResult();
  },

  /** 保存答题记录*/
  saveExamResult() {
    let that = this;
    http.requestData("POST", "LiveRoom/SaveExamResult", {
      po: this.data.po,
      manageId: this.data.inviteCode, //邀请码
      examId: this.data.answerInfo.Id, //试题id
      answerResult: this.data.answerKey == this.data.answerInfo.Answer ? 20 : 30, //选择的试题答案
      activeType: this.data.roomExtend.IsSaveActive == 1 ? "10" : (this.data.roomExtend.IsSaveActive == 2 ? "20" : "30") // 活动类型
    }).then(res => {
      that.setCacheExam(that.data.po);
      if(that.data.roomExtend.IsSaveActive==3){ //店长设置活动类型为不设置活动
        // http.showToast("管理没有设置活动奖励噢")
        that.setData({
          showPacket: true, //管理没有设置活动奖励, 直接提示谢谢参与
        })
        return;
      }
      //答对领奖励
      if (that.data.answerKey == that.data.answerInfo.Answer) {
        that.setData({
          showRedBg: true
        })
        //滚动到底部显示红包
        setTimeout(() => {
          that.setData({
            askTop: 250
          })
        }, 250);
      } else { //回答错误  直接提示谢谢参与
        that.setData({
          showPacket: true,
        })
      }
      that.setData({
        answerKey: ""  //将答案置空
      })
    }).catch(err => {
      //服务器异常情况
      http.showToast("网络繁忙，请稍后重试");
      that.setData({
        isLiveExam: false //初始参与活动状态
      })
    })
  },

  /** 领奖励 */
  robRedPacket() {
    let that = this;
    http.requestData("POST", "WeChat/WeChatTransfer", {
      po: this.data.po,
      mangerId: this.data.inviteCode,
      examId: this.data.answerInfo ? this.data.answerInfo.Id : ""
    }, true).then(res => {
      if (res.Tag == 10) {//领取成功
        that.setData({
          showPacket: true,
          robAward: {
            type: res.Extend.Type,
            data: res.Data
          }
        })
      } else { //领取失败
        http.showToast(res.Message);
      }
    }).catch(err => {
      that.setData({
        showRedBg: true
      })
      http.showToast("服务器繁忙，请稍后重试")
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    player = wx.createLivePlayerContext('my_player');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        // windows | mac 电脑pc端
        // Android | ios 手机端
        that.setData({
          platform: res.platform
        })
      }
    })

    app.globalData.seetimes = wx.getStorageSync('seetimes') ? wx.getStorageSync('seetimes') : []; //观看时长
    app.globalData.seetimes.forEach(item => {
      if (item.po == this.data.po) {
        this.data.seeTime = item.seeTime;
      }
    })
    this.setData({
      enterTime: "",
      isEnter: true,
      isReply: false,
      seeTime: this.data.seeTime,
      chatMsgTop: this.data.chatMsgList.length * 100,
    })

    // this.connectMQTT(); //mqtt 连接
    // this.queryExam(); //获取答题库
    // this.queryInviteCode(); //获取店长邀请码
    
    SocketTask.closeSocket(false);//防止socket重复多次连接
    this.connectSocket();//socket链接
    if (this.data.enterType == 2 && this.data.liveStatus == 30) {
      return;
    }
    this.queryLiveDetails(); //直播详情
    // this.getCouponData();
  },

  /** 礼品券信息 */
  getCouponData(){
    let that = this;
    http.requestData("GET","Coupon/GetItemInfo",{
      po: this.data.po
    }).then(res=>{
      if(res.Tag=="10"){
        if(res.Data){
          that.setData({
            couponData: res.Data,
            couponTime: res.Data.ShowMinute * 60  //分钟转化秒
          })
        }
      }else{
        http.showToast(res.Message)
      }
      that.queryLiveDetails(); //直播详情
    }).catch(err=>{
      that.queryLiveDetails(); //直播详情
    })
  },

  /**
   * 去聊天
   */
  bindChatTap() {
    this.setData({
      isFocus: true,
      inputShow: true
    })
  },

  /**
   * 输入聊天内容
   */
  inputMsg(e) {
    this.setData({
      inputVal: e.detail.value
    })
  },
  /**
   * 输入框获取焦点
   * @param {*} e 
   */
  inputFocus(e) {
    this.setData({
      inputHeight: e.detail.height
    })
  },
  /**
  * 输入框失去焦点
  * @param {*} e 
  */
  inputBlur() {
    let that = this;
    setTimeout(() => {
      that.setData({
        inputHeight: 20,
        inputShow: false,
        isFocus: false
      })
    }, 100);
  },
  /**
   * 聊天发送
   */
  sendMsgTap() {
    if (!this.data.inputVal) {
      return
    }
    if (!this.data.roomInfo) {
      return http.showToast("发送失败，请稍后重试");
    }
    let chatMsg = {
      po: this.data.po, //房间号
      name: config.NICKNAME(),
      mobile: config.TEL(),
      head: config.HEADURL(),
      role: this.data.roomInfo.HostAppletId == config.OPENID() ? true : false, //角色 true-主播，false-粉丝（观看者）
      type: 1, //1聊天，2直播商品连接，3点赞
      msg: this.data.inputVal  //消息内容
      // RoomId: this.data.po, //房间号
      // AppleId: "",
      // Quality: "",
      // Message: {}
    }
    SocketTask.sendSocketMsg(JSON.stringify(chatMsg));
    this.setData({
      inputVal: "" //发送完，消息置空
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setSeeTime();
    if (!this.data.isEnter) {
      return;
    }
    this.setData({
      isEnter: false
    })
    this.leaveTimeStore();
  },

  /** 
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setSeeTime();
    //如果没有执行onhide 这里记录离开直播时间
    if (this.data.isEnter) {
      this.leaveTimeStore();
    }
  },

  /** 保存本地观看直播时长 */
  setSeeTime(){
    if(this.data.liveStatus == 20){
      let isContain = false
      app.globalData.seetimes.forEach((item, i) => {
        if (item.po == this.data.po) {
          isContain = true;
          item.seeTime = this.data.seeTotal;
        }
      })
      if(!isContain){
        let seeItem = {
          po: this.data.po,
          seeTime: this.data.seeTotal
        }
        app.globalData.seetimes.push(seeItem);
      }
      wx.setStorageSync("seetimes", app.globalData.seetimes);
    }
  },

  /** 直播结束后清除该直播间保存的观看时长 */
  removeSeeTime(){
    if(app.globalData.seetimes.length>0){
      app.globalData.seetimes.forEach((item, i) => {
        if (item.po == this.data.po) {
          app.globalData.seetimes.splice(i, 1);//清除此条数据
        }
      })
      wx.setStorageSync("seetimes", app.globalData.seetimes);
    }
  },

  /** 保存离开直播间的时间  */
  leaveTimeStore() {
    clearTimeout(this.data.exitTimeout);
    clearInterval(this.data.redTimer); //清除直播计时器
    clearInterval(this.data.startTimer); //清除距直播开始倒计时
    clearInterval(this.data.posterTimer); //清除广告计时器
    SocketTask.closeSocket(true);
    if (this.data.liveStatus != 10) {
      this.leaveStopPlay();
    }
    //进来时是直播中，离开时是已结束 
    if (this.data.enterType == 2 && this.data.liveStatus == 30) {
      return;
    }
    if (this.data.enterType == 2) {//直播中离开
      this.saveLeavePlaying();
    } else if (this.data.enterType == 3) {//回放离开
      this.saveLeavePlayed();
    }
    //记录观看回放进度
    if (this.data.enterType == 3 && this.data.liveStatus == 30) {
      this.savePlaybackCurrent();
    }
    // mqtt.disconnect();
  },

  /** 后台保存开始观看直播的时间*/
  startPlayStore() {
    let that = this;
    http.requestData("POST", "Live/StartPlay", {
      po: this.data.po,
      Status: this.data.liveStatus
    }).then(res => {
    }).catch(err => {
    })
  },

  // 离开直播间，后台记录时间
  leaveStopPlay() {
    let that = this;
    http.requestData("POST", "Live/StopPlay", {
      po: this.data.po,
      Status: this.data.liveStatus
    }).then(res => {
    }).catch(err => {
    })
  },
  /** 保存直播中的离开时间 */
  saveLeavePlaying() {
    if (!this.data.enterTime || this.data.liveStatus == 30) {
      return;
    }
    let that = this;
    let leaveTime = utils.formatTime(new Date());
    let longTimes = utils.computeTimes(leaveTime, this.data.enterTime);
    // console.log("每次开始时间：", this.data.enterTime)
    // console.log("每次结束时间：", leaveTime)
    // console.log("每次观看时长：", longTimes)
    // let hms = utils.countTimes(longTimes);
    // let hmsTimes = hms[1]+":"+hms[2]+":"+hms[3];
    // console.log("观看时长",hmsTimes)
    http.requestData("POST", "Live/SavePlayTime", {
      PO: this.data.po, // 房间号
      CreateTime: this.data.enterTime,
      LeaveTime: leaveTime,  // 离开时间
      Times: longTimes, //观看时长(秒)
      Status: this.data.liveStatus, //直播状态
      MangerId: this.data.inviteCode
    }).then(res => {
      if (res.Tag == 10) {
        that.setData({
          online: res.Extend ? res.Extend.OnLine : 0
        })
      } else {
        // console.log("离开保存失败")
      }
    }).catch(e => {
      // console.log("离开保存异常")
    })
  },
  /** 保存观看回放的离开时间 */
  saveLeavePlayed() {
    if (!this.data.enterTime) {
      return;
    }
    let that = this;
    let leaveTime = utils.formatTime(new Date());
    let longTimes = utils.computeTimes(leaveTime, this.data.enterTime);
    http.requestData("POST", "Live/SavePlayBackTime", {
      PO: this.data.po, // 房间号
      CreateTime: this.data.enterTime,
      LeaveTime: leaveTime,  // 离开时间
      Times: longTimes, //观看时长(秒)
      MangerId: this.data.inviteCode
    }).then(res => {
    }).catch(e => {
    })
  },

  /** 每隔一分钟上报时长 */
  savePlayTimeV2() {
    if (!this.data.enterTime || this.data.liveStatus == 30) {
      return;
    }
    let that = this;
    let leaveTime = utils.formatTime(new Date());
    let longTimes = utils.computeTimes(leaveTime, this.data.enterTime);
    http.requestData("POST", "Live/SavePlayTimeV2", {
      PO: this.data.po, // 房间号
      CreateTime: this.data.enterTime,
      LeaveTime: leaveTime,  // 离开时间
      Times: longTimes, //观看时长(秒)
      Status: this.data.liveStatus, //直播状态
      MangerId: this.data.inviteCode
    }).then(res => {
      if (res.Tag == 10) {
        that.setData({
          online: res.Extend ? res.Extend.OnLine : 0
        })
        // if (res.Data && res.Data == 30 && that.data.roomInfo.Model==10) {//直播结束
        //   that.livePlayOver();
        // }
      } else {
        console.log("SavePlayTimeV2: 保存失败")
      }
    }).catch(e => {
      console.log("SavePlayTimeV2: 保存异常")
    })
  },

  /** 获取问答题目 */
  queryExam() {
    let that = this;
    http.requestData("GET", "Live/GetExam", {
      po: this.data.po
    }).then(res => {
      if (res.Tag == 10) {
        that.setData({
          answerInfo: res.Data
        })
      } else {
        // console.log("获取答题库失败")
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /** 获取店长邀请码 */
  queryInviteCode() {
    let that = this
    // 获取邀请码
    http.requestData("GET", "InviteHistory/GetInvite", {
      po: this.data.po
    }).then(res => {
      if (res.Tag == 10) {
        that.setData({
          inviteCode: res.Data,
          inviteAppletId: res.Description
        })
      } else {
        // console.log("获取店长邀请码失败")
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /** 活动设置 */
  activitySetTap() {
    if (this.data.liveStatus == 20) {
      return http.showToast("直播中不允许设置活动");
    }
    this.cancelMask();
    http.href("/pages/livePlayer/activitySet/index?po=" + this.data.po);
  },
  /** 活动详情 */
  activityInfoTap() {
    http.showToast("暂未开放");
    return;
    this.cancelMask();
    http.href("/pages/livePlayer/activityInfo/index?po=" + this.data.po);
  },

  /** 店长没有设置过活动 不允许转发邀请 */
  noShareTap() {
    http.showToast("请先设置保存活动");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    // 设置转发分享是否私密，如果私密则禁止微信二次转发
    wx.updateShareMenu({
      withShareTicket: true,
      isPrivateMessage: !this.data.shareFlag
    })
    this.cancelMask();
    return {
      title: this.data.roomInfo.Name,
      path: "/pages/livePlayer/liveBrief/index?po=" + this.data.po + "&invite=" + this.data.inviteCode + "&inviteId=" + this.data.inviteAppletId,
      success(res) {
        // console.log("分享成功==", res)
      },
      fail(err) {
        // console.log("分享失败==", err)
      }
    }
  },

  /** 点赞动画 */
  translate() {
    // 随机数 (左右摇摆幅度)
    let randomNum = this.randomNum(-30, 30);
    //laudCurrent是控制active的
    this.setData({
      laudCurrent: parseInt(Math.random() * 9)
    })
    // .active 是选择器
    this.animate('.laud-active', [{
      opacity: 1,
      translateY: 0,
      ease: 'else',
      scale: [.5, .5]
    }, {
      opacity: 0, //飘到顶部隐藏
      scale: [1, 1],
      translate: [randomNum, -250]
    }], 1500, function () {
      //动画完成后的回调函数
    }.bind(this))
  },
  randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        // return Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
        break;
      default:
        return 0;
        break;
    }
  },

  /** 横竖屏切换 */
  rotateScreenTap() {
    this.setData({
      isRotate: !this.data.isRotate,
    })
  },

  /** 跳过广告 */
  skipTap() {
    clearInterval(this.data.posterTimer);
    if (this.data.roomInfo.AdType == 10) { //视频
      let videoCtx = wx.createVideoContext('myVideo');
      videoCtx.pause();
    }
    if (this.data.roomInfo.AdType == 20) { //音频
      let audioCtx = wx.createAudioContext('myAudio');
      audioCtx.pause();
    }
    this.setData({
      posterShow: false,
      liveMuted: false
    })
  },

  /** 刷新视频流 */
  refreshTap() {
    wx.showLoading();
    player.stop();
    this.setData({
      playUrl: this.data.usePlayUrl,
    })
    setTimeout(() => {
      wx.hideLoading();
      player.play();
    }, 300);
  },

  /**播放进度变化 */
  videoTimeupdate(e) {
    this.data.videoCurrent = e.detail.currentTime != e.detail.duration ? e.detail.currentTime : 0;
  },

  /** 记录回放观看进度 */
  savePlaybackCurrent() {
    let cur = -1;
    app.globalData.playbacks.forEach((item, i) => {
      if (item.po == this.data.po) {
        cur = i
      }
    })
    if (cur != -1) {
      if (this.data.videoCurrent == 0) {//回放已看完
        app.globalData.playbacks.splice(cur, 1);//清除此条数据
      } else {
        app.globalData.playbacks[cur].current = this.data.videoCurrent;
      }

    } else {
      let itemBack = {
        po: this.data.po,
        current: this.data.videoCurrent
      }
      app.globalData.playbacks.push(itemBack);
    }
    wx.setStorageSync('playbacks', app.globalData.playbacks);
  },

  // 设置答题记录缓存
  setCacheExam(key) {
    const expTime = new Date().getTime() + 60 * 60 * 1000; // 设置过期时间为一个小时后
    const cacheData = {
      expTime: expTime
    }
    wx.setStorageSync(key, cacheData); // 将数据存入本地缓存
  },
  //读取答题记录缓存
  getCacheExam(key) {
    const cacheData = wx.getStorageSync(key);
    if (cacheData) {
      const currentTime = new Date().getTime();
      if (currentTime < cacheData.expTime) {
        return true;
      } else {
        wx.removeStorageSync(key); //清除过期缓存
      }
    }
    return false;
  },

  //保存请求错误日志信息
  saveLogErr(logMsg) {
    return;
    logMsg.openid = config.OPENID();
    let log = JSON.stringify(logMsg);
    http.saveLogErr("POST", "/api/Errors/SaveError", {
      po: this.data.po,
      log: log
    }).then(log => {
      if (log.Tag != 10) {
        http.showToast("错误日志保存失败")
      }
    }).catch(e => {
      http.showToast("错误日志保存异常")
    })
  },

})